#include "e_wifi_sta.h"


void event_wifi_handel(void *params, esp_event_base_t event_base, int32_t event_id, void *event_data) {
    switch (event_id) {
        case WIFI_EVENT_STA_START://wifi启动成功
            ESP_LOGI("WIFI", "wifi启动成功");
            esp_wifi_connect();
            break;
        case WIFI_EVENT_STA_CONNECTED:
            ESP_LOGI("WIFI", "wifi连接成功");
            break;
        case WIFI_EVENT_STA_DISCONNECTED:
            ESP_LOGI("WIFI", "wifi连接断开");
            break;
        default:
            break;
    }
}

void event_ip_handel(void *params, esp_event_base_t event_base, int32_t event_id, void *event_data) {
    if (event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
        ESP_LOGI("WIFI", "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
        ESP_LOGI("WIFI", "IP已获取，通知其他任务可以开始了");
        //通知其他任务可以开始了
        if (params != NULL) {
            TaskHandle_t *task_handel = (TaskHandle_t *) params;
            xTaskNotifyGive(task_handel);
        }
    }
}


void connect_wifi(wifi_config_local_t wifi, TaskHandle_t *task_handel) {
    //初始化非易失性存储
    nvs_flash_init();
    //创建事件循环
    esp_event_loop_create_default();
    //初始化netif
    esp_netif_init();
    esp_netif_create_default_wifi_sta();
    //注册事件
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, event_wifi_handel, NULL);
    esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, event_ip_handel, task_handel);
    //配置WiFi
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    if (wifi == KETING_WIFI) {
        wifi_config_t wifiConfig = WIFI_CONFIG_KETING();
        esp_wifi_set_config(WIFI_IF_STA, &wifiConfig);
    } else if (wifi == WOSHI_WIFI) {
        wifi_config_t wifiConfig = WIFI_CONFIG_WOSHI();
        esp_wifi_set_config(WIFI_IF_STA, &wifiConfig);
    }
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_start();
}
